﻿using Microsoft.EntityFrameworkCore;
using Super.Admin.EFCore;
using Super.Admin.Entities;
using Super.Admin.IServices;

namespace Super.Admin.Services
{
    /// <summary>
    /// 用户常用菜单设置服务实现类
    /// </summary>
    public class UserCommonPermissionService : BaseService, IUserCommonPermissionService
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context">操作的数据库上下文</param>
        public UserCommonPermissionService(SuperDataBaseDbContext context) : base(context) { }
        /// <summary>
        /// 查询用户常用菜单
        /// </summary>
        /// <param name="userId">用户id</param>
        /// <returns>常用菜单实体集合</returns>
        public IReadOnlyCollection<UserCommonPermissionEntity> GetUserCommonPermissions(int userId)
        {
            return Query<UserCommonPermissionEntity>(u => u.UserId == userId).Include(u => u.Permission).ToList();
        }
        /// <summary>
        /// 修改用户常用菜单
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="permissionIds"></param>
        public void UpdateUserCommonPermission(int userId, IEnumerable<int> permissionIds)
        {
            // 先查询所有的常用
            List<UserCommonPermissionEntity> userCommonPermissionEntities = Query<UserCommonPermissionEntity>(u => u.UserId == userId).ToList();
            // 删除已有的常用 
            if (userCommonPermissionEntities.Count > 0)
            {
                List<object[]> param = new List<object[]>();
                foreach (var common in userCommonPermissionEntities)
                {
                    param.Add(new object[] { common.UserId, common.PermissionId });
                }
                Deletes<UserCommonPermissionEntity>(param);
            }
            // 插入新的常用
            if (permissionIds.Count() > 0)
            {
                List<UserCommonPermissionEntity> list = new List<UserCommonPermissionEntity>();
                foreach (var id in permissionIds)
                {
                    list.Add(new UserCommonPermissionEntity { UserId = userId, PermissionId = id });
                }
                Insert<UserCommonPermissionEntity>(list);
            }
            base.Commit(); // 提交事务
        }

    }
}
